package pers.qianyu.month_202012.date_20201207.sliding_window;

import org.junit.*;

import java.util.*;

/**
 * 438. 找到字符串中所有字母异位词
 * https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/
 *
 * @author mizzle rain
 * @date 2020-12-07 17:50
 */
public class FindAnagrams {
    public List<Integer> findAnagrams(String s, String p) {
        if (p.length() > s.length()) {
            return new ArrayList<>();
        }
        int[] need = new int[26];
        int[] window = new int[26];
        List<Integer> res = new ArrayList<>();
        int left = 0, right = p.length() - 1;
        for (int i = 0; i < p.length(); i++) {
            need[p.charAt(i) - 'a']++;
            window[s.charAt(i) - 'a']++;
        }
        while (right < s.length() - 1) {
            if (isValid(window, need)) {
                res.add(left);
            }
            window[s.charAt(left++) - 'a']--;
            window[s.charAt(++right) - 'a']++;
        }
        if (isValid(window, need)) {
            res.add(left);
        }
        return res;
    }

    private boolean isValid(int[] window, int[] need) {
        for (int i = 0; i < 26; i++) {
            if (window[i] != need[i]) {
                return false;
            }
        }
        return true;
    }

    @Test
    public void test1() {
        String s = "cbaebabacd";
        String p = "abc";
        List<Integer> result = new FindAnagrams().findAnagrams(s, p);
        System.out.println("result = " + result);
    }
}
